package com.chidopi.cdf.dao;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

public abstract class AbstractBaseDaoImpl<T> implements IBaseDao<T> {
	private static Logger logger = LoggerFactory.getLogger(AbstractBaseDaoImpl.class);

	protected SimpleJdbcTemplate simpleJdbcTemplate;
	@Autowired
	public void init(DataSource datasource) {
		this.simpleJdbcTemplate = new SimpleJdbcTemplate(datasource);
		logger.debug("init: after new JdbcTemplate");
	}
	
	public int insert(String sql, T t){
		SqlParameterSource vo = new BeanPropertySqlParameterSource(t);
		KeyHolder keyHolder=new GeneratedKeyHolder();
		int ret = this.simpleJdbcTemplate.getNamedParameterJdbcOperations().update(sql,vo,keyHolder);
		if(ret > 0) return keyHolder.getKey().intValue();
		return ret;
	}

	public int execSQL(String sql, T t) {
		SqlParameterSource vo = new BeanPropertySqlParameterSource(t);
		return this.simpleJdbcTemplate.update(sql, vo);
	}

	public int getSeqNextValue(){
		String sql = " SELECT "+getSequenceName()+".nextval from dual";
		return this.simpleJdbcTemplate.queryForInt(sql);
	}
	public int getSeqCurrValue(){
		String sql = " SELECT "+getSequenceName()+".currval from dual";
		return this.simpleJdbcTemplate.queryForInt(sql);
	}

	protected abstract String getTable();
	protected abstract String getSequenceName();
	protected abstract RowMapper<T> getRowMapper();
}
